//
//  Emoticons.swift
//  01表情键盘
//
//  Created by 龚欣 on 15/7/7.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit

class EmoticonPackage: NSObject {
    var id : String?
    
    var emoticons : [Emoticon]?
    
    var groupName : String?
    
    init(id : String){
        self.id = id
    }
    
    static let packagesList = EmoticonPackage.packages()
    
    private class func packages() -> [EmoticonPackage]? {
        var list = [EmoticonPackage]()
        
        let p = EmoticonPackage(id: "")
        p.groupName = "最近使用"
        p.loadEmptyEmoticons()
        list.append(p)
        
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        let dict = NSDictionary(contentsOfFile: path!)!
        let array = dict["packages"] as! [[String : AnyObject]]
        
        for d in array {
            let p = EmoticonPackage(id: d["id"] as! String)
            p.loadEmoticons()
            p.loadEmptyEmoticons()
            list.append(p)
        }
        
        return list
    }
    
    class func emoticonAttributeStringWithString(string : String,font : UIFont) -> NSAttributedString?{
        let pattern = "\\[.*?\\]"
        
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
            
            let checkResult = regex.matchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: string.characters.count))
            var count = checkResult.count
            
            let strM = NSMutableAttributedString(string: string)
            
            while count > 0{
                let result = checkResult[--count]
                
                let  s = (string as NSString).substringWithRange(result.range)
                
                if let emoticon = emoticonWithString(s){
                    
                    let attrStr = EmoticonAttachment.emoticonString(emoticon, font: font)
                    
                    strM.replaceCharactersInRange(result.range, withAttributedString: attrStr)
                }
            
            }
            return strM
            
        }catch {
            print(error)
            
            return nil
        }
    }
    
    private class func emoticonWithString(string : String) -> Emoticon?{
        var emoticon : Emoticon?
        
        for package in packagesList! {
            emoticon = package.emoticons?.filter{ $0.chs == string }.last
            
            if emoticon != nil {
                break
            }
            
        }
        return emoticon
    }
    
    private func loadEmoticons(){
        
        let dict = NSDictionary(contentsOfFile: listPath())!
        groupName = dict["group_name_cn"] as? String
        let array = dict["emoticons"] as! [[String : String]]
        
        emoticons = [Emoticon]()
        var index = 0
        for d in array {
           emoticons?.append(Emoticon(id: id!, dict: d))
            
            index++
            if index == 20 {
                emoticons?.append(Emoticon(isRemoveButton: true))
                index = 0
            }
        }
    }
    
    private func loadEmptyEmoticons(){
        if emoticons == nil{
            emoticons = [Emoticon]()
        }
        
        let count = emoticons!.count % 21
        if count > 0 || emoticons?.count == 0 {
            for _ in count..<20 {
                emoticons?.append(Emoticon(isRemoveButton: false))
            }
            emoticons?.append(Emoticon(isRemoveButton: true))
        }
    }
    
    private func listPath() -> String{
        return EmoticonPackage.bundlePath().stringByAppendingPathComponent(id!).stringByAppendingPathComponent("info.plist")
    }
    
    private class func bundlePath() -> String{
        
       return NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons.bundle")
    }
    
    func appendFavouriteEmoticon(emoticon : Emoticon){
        let contain = emoticons!.contains(emoticon)
        
        if !contain {
            emoticons?.append(emoticon)
            
        }
        var result = emoticons
        
        result = result!.sort({ (e1, e2) -> Bool in
            e1.times > e2.times
        })
        
        if !contain{
            result?.removeLast()
        }
        
        emoticons = result
        
//        emoticons = emoticons?.sort({ (e1, e2) -> Bool in
//            e1.times > e2.times
//        })
//        
//        if !contain{
//            emoticons?.removeLast()
//        }
        
    }
    
}

class Emoticon: NSObject {
    
    var id : String?
 /// 表情对应的名字
    var chs : String?
 /// 表情对应的图片
    var png : String?
    
    var imagePath : String? {
        return png == nil ? nil : EmoticonPackage.bundlePath().stringByAppendingPathComponent(id!).stringByAppendingPathComponent(png!)
    }
    /// 表情苹果自带的code
    var code : String?{
        didSet{
            let scanner = NSScanner(string: code!)
            var result : UInt32 = 0
            scanner.scanHexInt(&result)
            
            emoji = "\(Character(UnicodeScalar(result)))"
        }
    }
    var emoji : String?
    
    var removeButton = false
    
    var times = 0
    
    init(isRemoveButton : Bool){
        super.init()
        removeButton = isRemoveButton
    }
    
    init(id : String,dict : [String : String]){
        super.init()
        self.id = id
        self.setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
}